package com.qn.servlet;

import com.alibaba.fastjson2.JSON;
import com.qn.entity.Product;
import com.qn.entity.ResultBean;
import com.qn.service.ProductServiceImpl;
import com.qn.service.ProductServiceInter;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/add")
public class AddServlet extends HttpServlet {

    //创建业务层对象
    private ProductServiceInter<Product> productServiceInter = new ProductServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //创建结果集对象
        ResultBean resultBean = new ResultBean(true);
        try {
            //获取表单提交的数据，存放到Map中
            Map<String, String[]> parameterMap = request.getParameterMap();
            //将parameterMap封装成一个对象
            Product product = new Product();
            //调用BeaUtils自动进行封装
            BeanUtils.populate(product,parameterMap);
            //调用业务的方法
            int row = productServiceInter.add(product);
            if (row>0) {
                //新增成功
                resultBean.setData("success");
            }else {
                //新增失败
                resultBean.setData("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultBean.setFlag(false);
            resultBean.setErrorMsg("添加服务器出现异常");
        }
        //回写数据
        response.getWriter().write(JSON.toJSONString(resultBean));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
